<template>
    <div class="common-container">
        <el-row class="top-actions" :gutter="10">
            <el-col :span="12" class="left-actions">
                <el-button type="success" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>新增
                </el-button>
                <el-button type="primary" @click="handleBatchVerify" :disabled="selectedRows.length === 0"
                    style="margin-left: 10px;">
                    <el-icon>
                        <Check />
                    </el-icon>批量核验
                </el-button>
                <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0"
                    style="margin-left: 10px;">
                    <el-icon>
                        <Delete />
                    </el-icon>批量删除
                </el-button>
            </el-col>
            <el-col :span="12" class="right-actions">
                <el-button type="default" @click="handleRefresh">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </el-col>
        </el-row>
        <el-row class="filter-bar" :gutter="20">
            <el-col :span="24">
                <el-date-picker v-model="filterForm.date" type="date" placeholder="请选择筛选日期" value-format="YYYY-MM-DD"
                    clearable style="margin-right: 10px;" />
                <el-cascader v-model="filterForm.lineLocationId" :options="locationOptions" placeholder="请选择站点"
                    clearable style="margin-right: 10px;" :disabled="locationOptions.length === 0" />
                <el-select v-model="filterForm.isApproval" placeholder="请选择状态" clearable
                    style="margin-right: 10px;width: 214px;">
                    <el-option value="已核验">已核验</el-option>
                    <el-option value="待核验">待核验</el-option>
                </el-select>
                <el-button type="primary" @click="handleFilter">筛选</el-button>
                <el-button type="default" @click="handleResetFilter" style="margin-left: 10px">重置</el-button>
            </el-col>
        </el-row>
        <div class="table-scroll-container">
            <el-table :data="tableData" stripe border style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="date" label="日期" />
                <el-table-column prop="locationName" label="站点" />
                <el-table-column prop="taskName" label="表计" />
                <el-table-column prop="value" label="数据" />
                <el-table-column label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.isApproval ? 'success' :
                            !scope.row.isApproval ? 'danger' : 'info'">
                            {{ getStatusText(scope.row.isApproval) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button size="small" type="warning" @click="handleVerify(scope.row)"
                            :disabled="scope.row.isApproval">核验</el-button>
                        <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :before-close="handleDialogClose"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="11">
                        <el-form-item label="日期" prop="date">
                            <el-date-picker v-model="formData.date" type="date" placeholder="请选择日期"
                                :disabled="isEditMode" value-format="YYYY-MM-DD" style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="站点" prop="locationName">
                            <el-cascader v-model="formData.locationName" :options="locationOptions" placeholder="请选择站点"
                                clearable style="margin-right: 10px;" @change="changeLocation"
                                v-if="!isEditMode && dialogVisible" :show-all-levels="false" />
                            <el-select v-model="formData.locationName" placeholder="请选择站点" v-else :disabled="isEditMode"
                                style="width: 200px;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="11">
                        <el-form-item label="表计" prop="taskName">
                            <el-select v-model="formData.taskName" filterable clearable placeholder="请输入表计名称"
                                :disabled="isEditMode || ammeterOptions.length == 0" style="width: 200px;"
                                @change="changeDianBiao">
                                <el-option v-for="item in ammeterOptions" :key="item.id" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="数据" prop="value">
                            <el-input-number v-model="formData.value" :controls="false" :min="0" placeholder="请输入表计数据">
                                <template #suffix>kWh</template>
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="22">
                        <el-form-item label="表计图片">
                            <el-image :src="formData.displayPictureUrl || formData.pictureId" alt="表计图片" class="meter-image" preview-teleported
                                :preview-src-list="[formData.displayPictureUrl || formData.pictureId]" v-if="isEditMode">
                                <template #error>
                                    <div class="meter-image-loading" />
                                </template>
                            </el-image>
                            <el-upload v-model:file-list="ammterImage" :action="`${baseURL}/sys/file/upload`"
                                class="upload-file" :headers="{ Authorization: 'Bearer ' + cookies.get('token') }"
                                :on-success="handleFileSuccess" :limit="1" list-type="picture"
                                accept="image/jpeg,image/png,image/webp" v-else>
                                <el-button type="primary" :disabled="ammterImage.length == 1">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="handleDialogClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
            </template>
        </el-dialog>


        <el-dialog v-model="verifyDialogVisible" :title="verifyDialogTitle" width="800px" :close-on-click-modal="false"
            @close="handleDialogClose">
            <div class="verify-content">
                <el-descriptions :column="3" border>
                    <el-descriptions-item label="日期" :width="100" :label-width="60">
                        {{ verifyData.date }}
                    </el-descriptions-item>
                    <el-descriptions-item label="站点" :width="100" :label-width="60">
                        {{ verifyData.locationName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="表计" :width="150" :label-width="60">
                        {{ verifyData.taskName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="数据">
                        <el-input-number v-model="formData.value" :controls="false" :min="0" placeholder="请输入表计数据">
                            <template #suffix>kWh</template>
                        </el-input-number>
                    </el-descriptions-item>
                </el-descriptions>
                <div class="image-container" style="margin-top: 20px;">
                    <el-image :src="verifyData.pictureId" alt="表计图片" class="large-meter-image" preview-teleported
                        :preview-src-list="[verifyData.pictureId]" v-if="verifyData.pictureId">
                        <template #error>
                            <div class="large-meter-image-loading"></div>
                        </template>
                    </el-image>
                    <div v-else style="text-align: center; padding: 20px; border: 1px dashed #ccc;">
                        无表计图片
                    </div>
                </div>
                <div v-if="isBatchVerify" style="margin-top: 20px;">
                    <div class="batch-navigation" style="margin-top: 15px; text-align: center;">
                        <el-button @click="prevVerifyItem" :disabled="currentVerifyIndex <= 0">上一个</el-button>
                        <span style="margin: 0 15px;">{{ currentVerifyIndex + 1 }} / {{ selectedRows.length }}</span>
                        <el-button @click="nextVerifyItem"
                            :disabled="currentVerifyIndex >= selectedRows.length - 1">下一个</el-button>
                    </div>
                </div>
            </div>
            <template #footer>
                <div style="display: flex; align-items: center; width: 100%;">
                    <div style="margin-left: auto;">
                        <el-button type="success" @click="handleVerifyResult()">核验</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>

        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[15, 30, 45, 60, 100]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick, reactive } from 'vue';
import { Plus, Refresh, Check, Delete } from '@element-plus/icons-vue';
import htglAPI from '@/api/htgl';
import { ElMessage, ElMessageBox } from 'element-plus';
import fileAPI from '@/api/file.js';
import optionsAPI from '@/api/options.js';
import { formatDate } from '@/utils/Format.js';
import { errorNotify } from '@/utils/Misc';
import { useCookies } from 'vue3-cookies';
const { cookies } = useCookies();
const baseURL = import.meta.env.VITE_API_BASE_URL;
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEditMode = ref(false);
const formRef = ref(null);
const formData = ref({
    id: null,
    date: "",
    locationId: '',
    locationName: '',
    taskName: '',
    taskId: '',
    value: 0,
    pictureId: ''
});
const filterForm = ref({
    date: '',
    locationId: "",
    lineLocationId: [],
    isApproval: null
});
const formRules = ref({
    date: [
        { required: true, message: '请选择日期', trigger: 'blur' }
    ],
    locationName: [
        { required: true, message: '请选择站点', trigger: 'change' },
    ],
    taskName: [
        { required: true, message: '请选择表计', trigger: 'change' },
    ],
    value: [
        { required: true, message: '请输入表计数据', trigger: 'change' },
        { type: 'number', min: 0, message: '表计数据不能为负数', trigger: 'change' }
    ]
});
const submitLoading = ref(false);
const locationOptions = ref([]);
const ammeterOptions = ref([]);
const ammterImage = ref([]);
const verifyDialogVisible = ref(false);
const verifyDialogTitle = ref('核验表计数据');
const verifyData = reactive({
    id: null,
    date: '',
    locationName: '',
    taskName: '',
    value: 0,
    pictureId: '',
    status: ''
});
const isBatchVerify = ref(false);
const selectedRows = ref([]);
const currentVerifyIndex = ref(0);
const handleFileSuccess = () => {
    formData.value.pictureId = ammterImage.value[0].response.sysFile.id;
};
const changeLocation = (value) => {
    formData.value.locationId = value[1];
    formData.value.taskId = ""
    formData.value.taskName = ""
    if (value[1]) {
        fetchDianBiao(value[1]);
    }
};
const changeDianBiao = (value) => {
    formData.value.taskId = value;
};
const fetchLineLocationTree = () => {
    optionsAPI.getSubstation().then(res => {
        locationOptions.value = res.data.treeList.map(item => ({
            value: item.id,
            label: item.name,
            children: item.locationTree.map(child => ({
                value: child.id,
                label: child.name
            }))
        })).sort((a, b) => a.label.localeCompare(b.label));
    }).catch(error => {
        errorNotify("DianLiangShuJu.vue", "fetchLineLocationTree", error);
        ElMessage.error('站点数据加载异常');
    });
};
const handleFilter = () => {
    currentPage.value = 1;
    fetchData();
};
const handleResetFilter = () => {
    filterForm.value = {
        date: '',
        lineLocationId: [],
        isApproval: null
    };
    currentPage.value = 1;
    fetchData();
};
const fetchData = () => {
    loading.value = true;
    console.log(filterForm.value.isApproval == "已核验" ? 1 : "待核验" ? 0 : null);
    const params = {
        date: filterForm.value.date,
        locationId: filterForm.value.lineLocationId[1] || '',
        isApproval: filterForm.value.isApproval == "已核验" ? 1 : filterForm.value.isApproval == "待核验" ? 0 : null,
        pageDto: {
            pageNo: currentPage.value,
            pageSize: pageSize.value,
            orderBy: 'updated_at desc'
        },
    };
    htglAPI.listDianLiang(params).then((res) => {
        tableData.value = res.data.page.list.map(item => {
            return {
                ...item,
                date: formatDate(item.date, 2),
                status: item.status || 'pending'
            };
        }).sort((a, b) => b.date.localeCompare(a.date));
        total.value = res.data?.page?.count || 0;
        loading.value = false;
    }).catch((error) => {
        errorNotify("DianLiangShuJu.vue", "fetchData", error);
        total.value = 0;
        loading.value = false;
    });
};
const fetchDianBiao = (id) => {
    optionsAPI.getDianBiao(id).then(res => {
        ammeterOptions.value = res.data.page.list.map(item => ({
            value: item.id,
            label: item.name
        }));
    }).catch(error => {
        errorNotify("DianLiangShuJu.vue", "fetchDianBiao", error);
    });
};
onMounted(() => {
    fetchData();
    fetchLineLocationTree();
});
const handleAdd = () => {
    dialogTitle.value = '添加表计数据';
    isEditMode.value = false;
    dialogVisible.value = true;
    nextTick(() => {
        resetFormData();
    });
};
const handleEdit = (row) => {
    dialogTitle.value = '编辑表计数据';
    isEditMode.value = true;
    dialogVisible.value = true;
    // 保存原始图片ID用于提交
    formData.value = {
        id: row.id,
        date: row.date,
        locationName: row.locationName,
        taskName: row.taskName,
        value: Number(row.value),
        pictureId: row.pictureId, // 保留原始ID
        originalPictureId: row.pictureId // 额外保存原始ID
    };
    if (row.pictureId) {
        fileAPI.downloadFile(row.pictureId)
            .then((res) => {
                if (res.data instanceof Blob) {
                    const blobUrl = URL.createObjectURL(res.data);
                    // 创建一个临时显示属性，不覆盖原始的pictureId
                    formData.value.displayPictureUrl = blobUrl;
                }
            }).catch((error) => {
                errorNotify("DianLiangShuJu.vue", "handleEdit", error);
            });
    }
};
const handleDialogClose = () => {
    dialogVisible.value = false;
    // 清理blob URL避免内存泄漏
    if (formData.value.displayPictureUrl) {
        URL.revokeObjectURL(formData.value.displayPictureUrl);
    }
    nextTick(() => {
        handleRefresh();
        resetFormData();
    });
};
const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            submitLoading.value = true;
            const submitData = {
                id: formData.value.id,
                date: formData.value.date,
                locationId: formData.value.locationId,
                taskId: formData.value.taskId,
                value: formData.value.value,
                // 编辑模式下使用原始图片ID，新增模式使用上传的图片ID
                pictureId: isEditMode.value && formData.value.originalPictureId ? formData.value.originalPictureId : formData.value.pictureId
            };
            htglAPI.saveDianLiang(submitData).then((res) => {
                submitLoading.value = false;
                handleDialogClose();
                handleRefresh();
                ElMessage.success('提交成功');
            }).catch((error) => {
                errorNotify("DianLiangShuJu.vue", "handleSubmit", error);
                submitLoading.value = false;
            });
        } else {
            return false;
        }
    });
};
const resetFormData = () => {
    formData.value = {
        id: null,
        date: "",
        locationId: '',
        locationName: '',
        taskId: '',
        taskName: '',
        value: 0,
        pictureId: '',
        originalPictureId: null,
        displayPictureUrl: null
    };
    ammterImage.value = [];

    if (formRef.value) {
        formRef.value.clearValidate();
    }
};
const handleRefresh = () => {
    fetchData();
};
const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchData();
};
const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchData();
};
const handleSelectionChange = (selection) => {
    selectedRows.value = selection;
};
const getStatusText = (isApproval) => {
    if (isApproval) {
        return "已核验"
    } else {
        return "待核验"
    }
};
const handleVerify = (row) => {
    verifyDialogTitle.value = '核验表计数据';
    isBatchVerify.value = false;
    Object.assign(verifyData, {
        id: row.id,
        date: row.date,
        locationName: row.locationName,
        taskName: row.taskName,
        value: row.value,
        pictureId: row.pictureId,
        status: row.status || 'pending'
    });


    if (row.pictureId) {
        fileAPI.downloadFile(row.pictureId)
            .then((res) => {
                if (res.data instanceof Blob) {
                    const blobUrl = URL.createObjectURL(res.data);
                    verifyData.pictureId = blobUrl;
                }
            }).catch((error) => {
                errorNotify("DianLiangShuJu.vue", "handleVerify", error);
            });
    }
    formData.value.id = row.id
    formData.value.value = row.value

    verifyDialogVisible.value = true;
};
const handleBatchVerify = () => {
    const pendingRows = selectedRows.value.filter(row => !row.isApproval);

    if (pendingRows.length === 0) {
        ElMessage.warning('请选择待核验的数据');
        return;
    }

    verifyDialogTitle.value = '批量核验表计数据';
    isBatchVerify.value = true;
    currentVerifyIndex.value = 0;

    selectedRows.value = pendingRows;

    loadVerifyData(0);
    verifyDialogVisible.value = true;
};
const loadVerifyData = (index) => {
    if (index < 0 || index >= selectedRows.value.length) return;

    // 清理旧的blob URL避免内存泄漏
    if (verifyData.pictureId && verifyData.pictureId.startsWith('blob:')) {
        URL.revokeObjectURL(verifyData.pictureId);
    }

    const row = selectedRows.value[index];
    Object.assign(verifyData, {
        id: row.id,
        date: row.date,
        locationName: row.locationName,
        taskName: row.taskName,
        value: row.value,
        pictureId: row.pictureId,
        status: row.status || 'pending'
    });
    formData.value.id = row.id;
    formData.value.value = row.value;

    if (row.pictureId) {
        fileAPI.downloadFile(row.pictureId)
            .then((res) => {
                if (res.data instanceof Blob) {
                    const blobUrl = URL.createObjectURL(res.data);
                    verifyData.pictureId = blobUrl;
                }
            }).catch((error) => {
                errorNotify("DianLiangShuJu.vue", "loadVerifyData", error);
            });
    }
};
const prevVerifyItem = () => {
    if (currentVerifyIndex.value > 0) {
        currentVerifyIndex.value--;
        loadVerifyData(currentVerifyIndex.value);
    }
};
const nextVerifyItem = () => {
    if (currentVerifyIndex.value < selectedRows.value.length - 1) {
        currentVerifyIndex.value++;
        loadVerifyData(currentVerifyIndex.value);
    }
};
const handleVerifyResult = () => {
    const submitData = {
        id: formData.value.id,
        value: formData.value.value,
    }
    htglAPI.approvalDailyDianLiang(submitData).then(() => {
        if (isBatchVerify.value && currentVerifyIndex.value < selectedRows.value.length - 1) {
            nextVerifyItem();
        } else if (isBatchVerify.value) {
            verifyDialogVisible.value = false;
            // 清理blob URL避免内存泄漏
            if (verifyData.pictureId && verifyData.pictureId.startsWith('blob:')) {
                URL.revokeObjectURL(verifyData.pictureId);
            }
            handleRefresh();
        } else {

            verifyDialogVisible.value = false;
            handleRefresh();
        }
    }).catch((error) => {
        errorNotify("DianLiangShuJu.vue", "handleVerifyResult", error);
        ElMessage.error('核验失败');
    });
};

const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除日期为${row.date}，站点为${row.locationName}的表计数据吗？`,
        '确认删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        loading.value = true;
        htglAPI.deleteDianLiang(row.id).then(() => {
            ElMessage.success('删除成功');
            handleRefresh();
        }).catch((error) => {
            errorNotify("DianLiangShuJu.vue", "handleDelete", error);
            ElMessage.error('删除失败');
        }).finally(() => {
            loading.value = false;
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

const handleBatchDelete = () => {
    ElMessageBox.confirm(
        `确定要删除选中的${selectedRows.value.length}条表计数据吗？`,
        '确认批量删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        loading.value = true;
        const ids = selectedRows.value.map(row => row.id).join(',');
        htglAPI.deleteDianLiang(ids).then(() => {
            ElMessage.success(`成功删除${selectedRows.value.length}条数据`);
            handleRefresh();
            selectedRows.value = [];
        }).catch((error) => {
            errorNotify("DianLiangShuJu.vue", "handleBatchDelete", error);
            ElMessage.error('批量删除失败');
        }).finally(() => {
            loading.value = false;
        });
    }).catch(() => {
        ElMessage.info('已取消批量删除');
    });
};

</script>

<style scoped>
:deep(.el-dialog) {
    margin-top: 5%;
}

.common-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    max-height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
}

.top-actions {
    margin-bottom: 20px;
    align-items: center;
}

.left-actions {
    text-align: left;
}

.right-actions {
    text-align: right;
}

.table-scroll-container {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 20px;
    max-height: calc(100vh - 290px);
}

.table-scroll-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.table-scroll-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.pagination-container {
    margin-top: auto;
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    position: sticky;
    bottom: 0;
    background-color: #fff;
    z-index: 10;
}

.preview-content {
    max-height: 400px;
    overflow-y: auto;
    padding: 10px;
}

.preview-content h4 {
    margin: 0 0 10px 0;
    color: #333;
}

.preview-content p {
    margin: 5px 0;
    font-size: 14px;
    line-height: 1.4;
    color: #666;
}

.preview-content strong {
    color: #333;
}

.upload-file {
    width: 50%;
    text-align: left;
}

.upload-file el-button {
    display: inline-block;
    margin-left: 0;
}

.meter-image {
    width: 150px;
    height: 120px;
    object-fit: contain;
    cursor: pointer;
}


.meter-image-loading {
    width: 150px;
    height: 120px;
    object-fit: contain;
    background-color: #f5f5f5;
    border-radius: 4px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
}

.meter-image-loading::before {
    content: "";
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: #409eff;
    animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}



.large-meter-image {
    width: 100%;
    height: auto;
    object-fit: contain;
    cursor: pointer;
}

.large-meter-image-loading {
    width: 100%;
    height: auto;
    object-fit: contain;
    background-color: #f5f5f5;
    border-radius: 4px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 420px;
}

.large-meter-image-loading::before {
    content: "";
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: #409eff;
    animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

.filter-bar {
    margin-bottom: 20px;
    text-align: left;
}

.verify-content {
    padding: 20px;
}

.image-container {
    text-align: center;
}


.batch-navigation {
    display: flex;
    justify-content: center;
    align-items: center;
}

.batch-navigation button {
    margin: 0 5px;
}

@keyframes pulse {

    0%,
    100% {
        opacity: 1;
        transform: scale(1);
    }

    50% {
        opacity: 0.5;
        transform: scale(0.7);
    }
}
</style>